import os

from django.conf import settings
from django.http import HttpResponse, Http404, JsonResponse
from django.shortcuts import render, redirect, reverse


def header_demo(request):
    return render(request, 'request_head.html')


def get_header(request):
    header = request.META.get('HTTP_SIGN', '')
    if header:
        value = {'header': header}
    else:
        value = {'header': None}
    return JsonResponse(value)


def cookie_demo(request):
    # 获取cookies
    # print(request.COOKIES.get('name'))
    return render(request, 'cookie.html')
    # 在响应内容中添加cookie
    # return HttpResponse('Hello Cookie')
    # response.set_cookie('name', value='name', max_age=3600)
    # return response
    # 在响应内容中删除cookie
    # return HttpResponse('Hello Cookie')
    # response.delete_cookie('name')
    # return response


def create_cookie(request):
    r = redirect(reverse('cookie'))
    # 添加cookie
    # response.set_cookie('name', value=request.COOKIES['name'])
    # 设置cookie的有效期时间为10秒
    r.set_signed_cookie('uuid', 'id', salt='mydj', max_age=10)
    print(r)
    return r


def get_cookie(request):
    cookie_exist = request.COOKIES.get('uuid')
    print(f'cookie_exist   {cookie_exist}')
    if cookie_exist:
        try:
            request.get_signed_cookie('uuid', salt='mydj')
        except:
            raise Http404('当前cookie无效')
        return HttpResponse(f'当前cookie为{cookie_exist}')
    else:
        raise Http404('当前访问没有cookie')


def index(request):
    # 使用method属性判断请求方式
    if request.method == 'GET':
        # 类方法
        print('dir(request)', [a for a in dir(request) if not a.startswith('__')])
        print(request.is_secure())
        print(request.get_host())
        print(request.get_full_path())
        # 属性的使用
        print(request.META)
        print(request.FILES)
        print(request.COOKIES)
        print(request.content_type)
        print(request.content_params)
        print(request.scheme)
        # 获取get 请求的请求参数
        print(request.GET.get('user', ''))
        return render(request, 'index_views.html')
    elif request.method == 'POST':
        print('post', request.POST.get('user', ''))
        return render(request, 'index_views.html')
    return "请求方法错误"


def upload(request):
    if request.method == 'POST':
        print(f'request.FILES{request.FILES}')
        myfile = request.FILES.get('myfile', None)
        if not myfile:
            return HttpResponse('no files for upload')
        # 打开特定的文件进行二进制的写操作
        f = open(os.path.join('D:\\upload', myfile.name), 'wb+')
        # 分快写入文件
        for chunk in myfile.chunks():
            f.write(chunk)
        f.close()
        return HttpResponse('upload success')
    else:
        return render(request, 'upload.html')
